package com.mvp.method2.imvp;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/3/6.
 */

public class BasePresenter<V extends BaseView> {

    private Reference<V> mRefView;
    private CompositeDisposable mCompositeDisposable;

    public void attachView(V mView) {
        this.mRefView = new WeakReference<V>(mView);
    }

    public void detachView() {
        if (this.mRefView != null) {
            this.mRefView.clear();
            this.mRefView = null;
        }
        onUnSubscribe();
    }

    protected V getView() {
        if (!isViewAttached())
            throw new IllegalStateException("view is not attached");
        return mRefView.get();
    }

    private boolean isViewAttached() {
        return mRefView != null && mRefView.get() != null;
    }

    protected void addSubscription(Observable observable, DisposableObserver observer) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(observer);

        observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer);
    }

    //RxJava取消注册，以避免内存泄露
    private void onUnSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }
}
